﻿/******************************************************************
 * 功能描述：网络相关方法帮助类，用于包装大部分网络相关方法
 * 创建时间：2013-11-14
 * 作者：Panxinming
 * 版本：1.0
 * 修订描述：
 * 最后修订日期：
 ******************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace EMoney.IStock.Client.Framework
{
    public class NetHelper
    {
        private string method = "GET";
        public System.Text.Encoding encode = Encoding.GetEncoding("utf-8");

        public static string GetWebClientIP()
        {
            return "";
        }

        /// <summary>
        /// GET方式提交，可指定字符集
        /// </summary>
        /// <param name="UrlString"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public string GetClientBySocket(string UrlString, System.Text.Encoding encode)
        {

            this.encode = encode;
            return GetClientBySocket(UrlString);
        }

        /// <summary>
        /// GET方式，默认字符集，本项目为gbk
        /// </summary>
        /// <param name="UrlString"></param>
        /// <returns></returns>
        public string GetClientBySocket(string UrlString,string reqMethod = "GET")
        {
            try
            {
                method = reqMethod;
                byte[] data = GetData(UrlString);
                return encode.GetString(data);
            }
            catch
            {
                return "";
            }
        }

        public byte[] GetData(string url)
        {
            return GetData(url, "");
        }

        private byte[] GetData(string UrlString, string updata)
        {
            string host;
            int port = 80;
            if (UrlString.StartsWith("http://"))
            {
                string temp = UrlString.Trim();
                temp = temp.Substring(7, temp.Length - 7);
                if (temp.IndexOf("/") == -1)
                {
                    host = temp;
                }
                else
                {
                    host = temp.Substring(0, temp.IndexOf("/"));
                }
                int portIndex = host.IndexOf(":");
                if (portIndex != -1)
                {
                    port = int.Parse(host.Substring(portIndex + 1));
                    host = host.Substring(0, portIndex);
                }
            }
            else
            {
                host = UrlString.Substring(0, UrlString.IndexOf("/"));
            }

            IPAddress[] ips = Dns.GetHostAddresses(host);
            IPAddress ip = ips[0];
            foreach (IPAddress _ip in ips)
            {
                if (_ip.AddressFamily.ToString() == "InterNetwork")
                    ip = _ip;
            }
            IPEndPoint serverhost = new IPEndPoint(ip, port);
            Socket clientSocket = null;
            try
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(serverhost);

                string httpReq = method + " " + UrlString + " HTTP/1.1\r\n";
                httpReq += "Host:" + host + "\r\n";
                httpReq += "Content-Type: application/x-www-form-urlencoded;Charset=" + encode.BodyName + "\r\n";
                if (method.ToUpper().Trim() == "POST")
                {
                    httpReq += "Content-length:" + updata.Length + "\r\n";
                }
                httpReq += "Connection: close\r\n\r\n";
                httpReq += updata;
                StringBuilder txtHTML = new StringBuilder();

                clientSocket.Send(encode.GetBytes(httpReq));
                Byte[] buffer = new byte[10240];
                int byteCount = clientSocket.Receive(buffer, buffer.Length, 0);
                List<byte> bLst = new List<byte>();
                AddByte(bLst, buffer, byteCount);
                while (byteCount > 0)
                {
                    byteCount = clientSocket.Receive(buffer, buffer.Length, 0);
                    AddByte(bLst, buffer, byteCount);

                }
                byte[] bbs = new byte[bLst.Count];
                for (int i = 0; i < bLst.Count; i++)
                {
                    bbs[i] = bLst[i];
                }

                var str = encode.GetString(bbs, 0, bbs.Length);
                //判断页面状态
                string strState = string.Empty;
                for (int i = 0; i < bbs.Length; i++)
                {
                    if (bbs[i] == '\r' && bbs[i + 1] == '\n')
                    {
                        strState = this.encode.GetString(bbs, 0, i);
                        break;
                    }
                }
                var ss = strState.Substring(strState.IndexOf(' ') + 1);
                if (ss != "200 OK")
                {
                    throw new Exception(ss);
                }
                int dataIndex = 0;
                for (int i = 0; i < bbs.Length; i++)
                {
                    if (bbs[i] == '\r' && bbs[i + 1] == '\n' && bbs[i + 2] == '\r' && bbs[i + 3] == '\n')
                    {
                        dataIndex = i + 4;
                        break;
                    }
                }
                byte[] data = new byte[bbs.Length - dataIndex];
                for (int i = dataIndex, j = 0; i < bbs.Length; i++, j++)
                {
                    data[j] = bbs[i];
                }
                return data;
            }
            catch (Exception err)
            {
                throw new Exception(err.Message + "url:" + UrlString);
                throw err;
            }
            finally
            {
                if (clientSocket != null)
                {
                    try
                    {
                        clientSocket.Close();
                    }
                    catch
                    {

                    }
                }
            }
        }

        void AddByte(List<byte> lst, byte[] data, int count)
        {
            for (int i = 0; i < count; i++)
            {
                lst.Add(data[i]);
            }
        }

        public static string PostData(string postcontent, string url)
        {
            byte[] byte1 = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(postcontent);

            string urlPage = url;
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;

            Encoding encoding = Encoding.GetEncoding("UTF-8");
            //byte[] data = encoding.GetBytes(xmlMsg);
            // 准备请求...
            // 设置参数
            request = WebRequest.Create(urlPage) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/json";

            //request.ContentType = "multipart/form-data";
            request.ContentLength = byte1.Length;
            outstream = request.GetRequestStream();
            outstream.Write(byte1, 0, byte1.Length);
            outstream.Flush();
            outstream.Close();
            //发送请求并获取相应回应数据
            response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            instream = response.GetResponseStream();
            sr = new StreamReader(instream, encoding);
            //返回结果网页（html）代码
            string content = sr.ReadToEnd();
            sr.Close();
            return content;
        }
    }
}
